const http = require('http');

console.log('Testing API endpoints...');

// 测试获取文档详情API
const options = {
  hostname: 'localhost',
  port: 3000,
  path: '/api/documents/1',
  method: 'GET'
};

const req = http.request(options, (res) => {
  console.log(`Status: ${res.statusCode}`);
  console.log(`Headers: ${JSON.stringify(res.headers)}`);
  
  let data = '';
  res.on('data', (chunk) => {
    data += chunk;
  });
  
  res.on('end', () => {
    console.log('Response body:', data);
  });
});

req.on('error', (error) => {
  console.error('Error:', error);
});

req.end();

// 测试登录API
function testLogin() {
  const loginData = JSON.stringify({
    username: 'testuser',
    password: 'testpass'
  });

  console.log('Sending login data:', loginData);

  const loginOptions = {
    hostname: 'localhost',
    port: 3000,
    path: '/api/login',
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Content-Length': Buffer.byteLength(loginData)
    }
  };

  const loginReq = http.request(loginOptions, (res) => {
    let data = '';
    
    console.log('Login Response Status Code:', res.statusCode);
    
    res.on('data', (chunk) => {
      data += chunk;
    });
    
    res.on('end', () => {
      console.log('Login Response Body:', data);
      
      // 如果登录成功，测试获取文档列表
      if (res.statusCode === 200) {
        const userData = JSON.parse(data);
        testGetDocuments(userData.user.id);
      }
    });
  });

  loginReq.on('error', (error) => {
    console.error('Login Request Error:', error.message);
  });

  loginReq.write(loginData);
  loginReq.end();
}

// 测试获取文档列表
function testGetDocuments(userId) {
  console.log('Testing get documents for user:', userId);
  
  const options = {
    hostname: 'localhost',
    port: 3000,
    path: `/api/documents/${userId}`,
    method: 'GET',
    headers: {
      'Content-Type': 'application/json'
    }
  };

  const req = http.request(options, (res) => {
    let data = '';
    
    console.log('Documents Response Status Code:', res.statusCode);
    
    res.on('data', (chunk) => {
      data += chunk;
    });
    
    res.on('end', () => {
      console.log('Documents Response Body:', data);
    });
  });

  req.on('error', (error) => {
    console.error('Documents Request Error:', error.message);
  });

  req.end();
}

// 执行测试
testLogin();